package com.application.Activity;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Network.Protocol;
import com.application.outdoor.InvoikeServices.AvatarInvoike;
import com.application.outdoor.InvoikeServices.CommonInvoike;
import com.application.outdoor.InvoikeServices.HeThongInvoike;
import com.application.outdoor.adapter.GroupEntity;
import com.application.outdoor.adapter.SubjectEntity;
import com.application.outdoor.pojo.NguoiDungPOJO;
import com.application.outdoor.pojo.NhomPOJO;

public class od_MainActivity extends Activity {
	LocalActivityManager localActivity;
	Button btnTinNhan;
	TextView txtTenDangNhap;
	public static Runnable raRefeshSoTinNhan;
	private static ProgressDialog mProgcess;
	AsyncTask<String, Integer, Integer> mUpAvatarTask;
	public static Handler hdShowProcess = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.e(Protocol.TAG, "handler message");
			Bundle b = msg.getData();
			if (b != null) {
				String value = b.getString("KEY");
				String title = b.getString(Protocol.NOI_DUNG);

				if (value != null && value.equals("SHOW") && !mProgcess.isShowing()) {
					mProgcess.setMessage(title);
					mProgcess.show();
				} else if (value != null && value.equals("DIS") && mProgcess.isShowing()) {
					mProgcess.dismiss();
				}
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.od_activity_main);

		ActivityController.arrActivity.add(this);
		getSoTinNhan();
		btnTinNhan = (Button) findViewById(R.id.btnSoTinNhan);
		txtTenDangNhap = (TextView) findViewById(R.id.txtTenDanNhap);

		btnTinNhan.setText(CommonUtilities.soTinNhan + "");
		txtTenDangNhap.setText(CommonUtilities.nguoiDung.getTenDangNhap());
		TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
		Resources res = getResources();
		localActivity = new LocalActivityManager(this, false);
		TabHost.TabSpec spSubject, spContact;
		Intent iContact, iSubject;

		localActivity.dispatchCreate(savedInstanceState);
		tabHost.setup(localActivity);

		iContact = new Intent().setClass(this, od_ContactActivity.class);
		iSubject = new Intent().setClass(this, od_SubjectActivity.class);
		spContact = tabHost.newTabSpec("contact")
				.setIndicator("Danh sách liên lạc", res.getDrawable(R.drawable.img_group)).setContent(iContact);

		spSubject = tabHost.newTabSpec("subject")
				.setIndicator("Danh sách chủ đề", res.getDrawable(R.drawable.ic_blue_discuss)).setContent(iSubject);
		tabHost.addTab(spContact);
		tabHost.addTab(spSubject);
		tabHost.setCurrentTab(0);
		btnTinNhan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Intent iTinNhan=new
				// Intent(getBaseContext(),od_TinNhanActivity.class);
				// startActivity(iTinNhan);
			}
		});
		btnTinNhan.setVisibility(View.GONE);
		txtTenDangNhap.setVisibility(View.GONE);
		raRefeshSoTinNhan = new Runnable() {

			@Override
			public void run() {
				btnTinNhan.setText(CommonUtilities.soTinNhan + "");
				if (CommonUtilities.soTinNhan <= 0) {
					btnTinNhan.setVisibility(View.GONE);
				} else {
					btnTinNhan.setVisibility(View.VISIBLE);
				}
			}
		};
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				getSoTinNhan();
			}
		});
		t.start();
	mProgcess=	new ProgressDialog(od_MainActivity.this);
	}

	private void getSoTinNhan() {
		Log.d(Protocol.TAG, "od_Main getSoTinNhan");
		try {
			String data = new HeThongInvoike().getSoTinNhanOffline(CommonUtilities.nguoiDung.getTenDangNhap()).trim();

			CommonUtilities.soTinNhan = Integer.parseInt(data);
			Log.d(Protocol.TAG, "Đã lấy  số tin nhắn" + CommonUtilities.soTinNhan);
			if (CommonUtilities.soTinNhan > 0)
				GCMIntentService.notification(od_MainActivity.this, "Bạn có " + data + " tin nhắn offline.",
						od_TinNhanActivity.class, null);
		} catch (Exception e) {
			CommonUtilities.soTinNhan = 0;
			Log.d(Protocol.TAG, "Khong lay dc sl tin nhan" + e.getMessage());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.od_omnu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.mnuTaoNhom: {
			AlertDialog.Builder builder = new AlertDialog.Builder(od_MainActivity.this);
			builder.setTitle("Tạo nhóm mới");
			builder.setMessage("Tên nhóm");
			final EditText txtTenNhom = new EditText(od_MainActivity.this);
			builder.setView(txtTenNhom);
			builder.setCancelable(false);
			builder.setNegativeButton("Hủy bỏ", null);
			builder.setPositiveButton("Tạo nhóm", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String tenNhom = txtTenNhom.getText().toString();
					String nguoiTao = CommonUtilities.nguoiDung.getTenDangNhap();
					try {
						String rs = new CommonInvoike().taoNhom(nguoiTao, tenNhom).trim();
						if (rs != null && !rs.equals(Protocol.SERVER_ERROR)) {
							int idNhom = Integer.parseInt(rs);
							NhomPOJO nhom = new NhomPOJO();
							nhom.setId(idNhom);
							nhom.setNguoiTao(nguoiTao);
							nhom.setTenNhom(tenNhom);

							ArrayList<NguoiDungPOJO> lstMember = new ArrayList<NguoiDungPOJO>();
							lstMember.add(CommonUtilities.nguoiDung);

							GroupEntity group = new GroupEntity(nhom, lstMember);

							SubjectEntity subject = new SubjectEntity();
							subject.setNhom(nhom);

							CommonUtilities.contacts.getData().add(group);
							Handler handler = new Handler();
							handler.post(od_ContactActivity.raRefreshData);
							CommonUtilities.subjects.getData().add(subject);
							handler.post(od_SubjectActivity.raRefreshData);
							NetworkController._peer.account.isThanhLapNhom = true;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
			builder.create().show();
		}
			break;
		case R.id.mnuXemTinNhan:
			Intent iTinNhan = new Intent(getBaseContext(), od_TinNhanActivity.class);
			startActivity(iTinNhan);
			break;
		default:
			break;
		}
		return false;

	}

	@Override
	public void onResume() {
		super.onResume();
		btnTinNhan.setText(CommonUtilities.soTinNhan + "");
		Log.d(Protocol.TAG, "onResume od_Main " + CommonUtilities.soTinNhan);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d("PEERDROID", " vao on key down");
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Thoát khỏi chương trình ?").setCancelable(false)
					.setPositiveButton("Có", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							if (NetworkController._peer.getAccount().isThanhLapNhom) {
								NetworkController._peer.getAccount().isThanhLapNhom = false;
							}
							finish();

						}
					}).setNegativeButton("Không", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255)));
			alert.show();

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public synchronized void onActivityResult(final int requestCode, int resultCode, final Intent data) {
		Log.d(Protocol.TAG, "onActivityResult " + requestCode);
		if (requestCode == od_ContactActivity.MNU_CHANGE_AVATAR && data != null) {
			String path = data.getStringExtra(FrmSelectFile.RESULT_PATH);
			if (path != null && path.trim().length() > 0) {
				initUpAvatarTask();
				mUpAvatarTask.execute(CommonUtilities.nguoiDung.getTenDangNhap(), path);
			}

		}
	}

	private void initUpAvatarTask() {
		mUpAvatarTask = new AsyncTask<String, Integer, Integer>() {

			@Override
			protected Integer doInBackground(String... params) {
				try {
					new AvatarInvoike().setAvatar(params[0], params[1]);
					return 0;
				} catch (ClientProtocolException e) {
					Log.d(Protocol.TAG, "KO the Up avatar" + e.getMessage());
					return -1;
				} catch (IOException e) {
					Log.d(Protocol.TAG, "KO the DOC  avatar" + e.getMessage());
					return -2;
				}

			}

			@Override
			protected void onPostExecute(Integer rs) {
				new Handler().post(od_ContactActivity.raRefreshData);
				if (rs == -1) {
					MESApplication
							.showDialog(od_MainActivity.this, "Đổi Avatar - Lỗi", "Không thể upload lên máy chủ!");
				} else if (rs == -2) {
					MESApplication.showDialog(od_MainActivity.this, "Đổi Avatar - Lỗi", "Hãy chọn tập tin hình ảnh!");
				}
			}

		};
	}

}
